<template>
  <van-pull-refresh v-model="loading" @refresh="onRefresh">
    <div class="box" @scroll.passive="onScroll" v-if="orderList.length>0">
      <div class="item" v-for="i in orderList" :key="i._id">
        <div class="item_top">
          <p>{{ dayjs(i.time).format("YYYY-MM-DD") }}</p>
          <div
            style="
              display: flex;
              justify-content: space-between;
              align-items: center;
            "
          >
            <span>提醒我</span>
            <van-switch
              active-color="#ffb900"
              v-model="i.remind"
              inactive-color="#ffb900"
              @change="chanremind(i._id)"
            />
          </div>
        </div>
        <div class="item_bot">
          <div class="item_bot1">
            <img src="/1.jpg" alt="" />
            <div>
              <p>{{ i.service }}</p>
              <p>理发师：{{ i?.stylistId?.name }}</p>
              <p>地址：{{ i?.salonId?.name }}</p>
              <p
                style="
                  white-space: nowrap;
                  overflow: hidden;
                  text-overflow: ellipsis;
                "
              >
                服务：{{ i?.serviceId?.name || i?.packageId?.name }}
              </p>
            </div>
          </div>
          <div class="item_bot2">
            <button @click="quxiao(i)">取消订单</button>
            <button @click="chanstatus(i)" :disabled="i.remind" :style="{backgroundColor:!i.remind?'#ffb900':'#ff781f'}">{{ i.remind?"等待商家确认":"立即使用" }}</button>
          </div>
        </div>
      </div>
    </div>
    <van-empty image-size="200" v-else description="暂无订单" />
  </van-pull-refresh>
</template>

<script setup >
import { ref, reactive, onMounted } from "vue";
import dayjs from "dayjs";
import axios from "axios";
import {
  showConfirmDialog,
  showSuccessToast,
  showFailToast,
  showLoadingToast,
  showToast,
} from "vant";
axios.defaults.baseURL = "http://127.0.0.1:3000/shopfront";
const orderList = ref([]);

const getorder = async () => {
  let {data: { data }} = await axios.get(
    `/getorder?page=${page.value}&pagesize=${pagesize.value}`
  );
  orderList.value = data.filter((i) => i.status == 0);
};

const loading = ref(false);
const loadingMore = ref(false);
const page = ref(1); // 当前页数
const pagesize = ref(10);
const onRefresh = async () => {
  loading.value = true;
  page.value = 1;
  orderList.value = [];
  await getorder();
  setTimeout(() => {
    showToast("刷新成功");
    loading.value = false;
  }, 1000);
};

onMounted(() => {
  getorder();
});

const quxiao = (i) => {
  let obj = {
    refund_amount: i.amout, // 确保属性名正确
    trade_no: i.trade,
  };
  showConfirmDialog({
    title: "取消订阅",
    message: "确定取消订阅吗？",
  })
    .then(() => {
      axios
        .post("/api/refund", obj)
        .then((response) => {
          if (response.data.code === 200) {
            console.log("退款请求成功", response.data.result);
            // 更新订单状态为已退款
            axios
              .put(`/chanrefund?_id=${i._id}`)
              .then((res) => {
                if (res.data.code === 200) {
                  showSuccessToast("退款成功！");
                  getorder();
                }
              })
              .catch((error) => {
                showFailToast("退款失败");
              });
          } else {
            console.error("退款请求失败", response.data);
          }
        })
        .catch((error) => {
          console.error("发送退款请求失败", error);
        });
    })
    .catch(() => {
      console.log("用户取消了操作");
    });
};

// 改变立即使用
const chanstatus = async (info) => {
  if(info.remind){
    showToast('已提醒商家确认,请勿重复操作');
    return;
  }
  showConfirmDialog({
    title: "使用",
    message: "确定使用吗？"
  })
    .then(() => {
      chanremind(info._id)
      showToast("已提醒商家确认");
    })
    .catch(() => {
      // on cancel
      showToast('取消使用')
    });
};

// 等待商家确认
const chanremind = async (id) => {
  let {
    data: { code },
  } = await axios.put(`/chanremind?_id=${id}`);
  if (code == 200) {
    getorder();
  }
};

// 添加触底加载功能
const handleLoadMore = async () => {
  // 防止重复加载
  if (loadingMore.value) return;

  loadingMore.value = true;

  // 显示加载提示
  showLoadingToast({
    message: "加载中...",
    forbidClick: true,
  });
  try {
    const {
      data: { data },
    } = await axios.get(
      `/getorder?page=${page.value}&pagesize=${pagesize.value}`
    );

    if (data.length > 0) {
      orderList.value.push(...data.filter((i) => i.status == 0)); // 追加新数据
      page.value++; // 更新页码
    } else {
      showToast("没有更多数据了");
    }
  } catch (error) {
    console.error("加载更多数据失败", error);
  } finally {
    loadingMore.value = false; // 无论如何都要重置加载状态
  }
};
const onScroll = (event) => {
  const { scrollHeight, scrollTop, clientHeight } = event.target;
  if (scrollTop + clientHeight >= scrollHeight - 10 && !loadingMore.value) {
    handleLoadMore(); // 调用加载更多数据的方法
  }
};
</script>
<style  scoped>
.box {
  width: 100%;
  height: 620px;
  padding: 0 10px;
  padding-bottom: 30px;
  box-sizing: border-box;
  overflow-y: scroll;
}
.box::-webkit-scrollbar {
  display: none;
}

.item {
  display: flex;
  width: 100%;
  height: 150px;
  justify-content: space-between;
  flex-direction: column;
  align-items: center;
  box-sizing: border-box;
  margin: 20px 0;
  border: 1px solid #ccc;
  
  border-radius: 10px;
}
.item_top {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #ccc;
  width: 100%;
  height: 20%;
  padding: 0 10px;
  box-sizing: border-box;
}
.item_bot {
  display: flex;
  width: 100%;
  height: 80%;
  flex-direction: column;
  justify-content: space-between;
  align-items: center;
}
.item_bot1 {
  width: 100%;
  height: 70%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.item_bot1 img {
  width: 23%;
  height: 90%;
  border-radius: 10%;
}
.item_bot1 div {
  width: 70%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
}

.item_bot2 {
  width: 100%;
  height: 40%;
  display: flex;
  justify-content: space-around;
  align-items: center;
}

.item_bot2 button:nth-child(1) {
  width: 40%;
  height: 70%;
  border: 1px solid #ffb900;
  border-radius: 10px;
  color: #ffb900;
  background-color: #ffffff;
}
.item_bot2 button:nth-child(2) {
  width: 40%;
  height: 70%;
  border: 1px solid #ffb900;
  border-radius: 10px;
  color: #ffffff;
  background-color: #ffb900;
}
</style>